package com.fish.web.pay;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.alipay.config.AlipayConfig;
import com.alipay.util.AlipaySubmit;
import com.alipay.util.Md5Encrypt;
import com.fish.account.po.Recharges;
import com.fish.common.web.BaseAction;
import com.fish.service.account.RechargesService;

public class AlipayAction extends BaseAction {
	private static final long serialVersionUID = 2249886988345508912L;
	private static final Log loger = LogFactory.getLog(AlipayAction.class);

	private RechargesService rechargesService;
	private String totalFee;

	public String goToPagChannel() {
		// 支付类型
		String payment_type = "1";
		// 必填，不能修改
		// 服务器异步通知页面路径
		String notify_url = "http://www.vdoany.com/pay/goToAlipay.do";
		// 需http://格式的完整路径，不能加?id=123这类自定义参数

		// 页面跳转同步通知页面路径
		String return_url = "http://www.vdoany.com/pay/aliPayCallback.do";
		// 需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/

		// 卖家支付宝帐户
		String seller_email = "405192832@qq.com";
		// 必填

		// 商户订单号
		String out_trade_no = this.getNewUUID();
		// 商户网站订单系统中唯一订单号，必填

		// 订单名称
		String subject = "平台充值";
		// 必填

		// 付款金额
		String total_fee = totalFee;
		loger.info("通过支付宝，充值金额total_fee:" + total_fee);
		// 必填

		// 订单描述

		String body = "平台充值即时到帐";
		// 商品展示地址
		String show_url = "http://www.qiqufang.com";
		// 需以http://开头的完整路径，例如：http://www.xxx.com/myorder.html

		// 防钓鱼时间戳
		String anti_phishing_key = "";
		// 若要使用请调用类文件submit中的query_timestamp函数

		// 客户端的IP地址
		String exter_invoke_ip = "";
		// 非局域网的外网IP地址，如：221.0.0.1

		// 把请求参数打包成数组
		Map<String, String> sParaTemp = new HashMap<String, String>();
		sParaTemp.put("service", "create_direct_pay_by_user");
		sParaTemp.put("partner", AlipayConfig.partner);
		sParaTemp.put("_input_charset", AlipayConfig.input_charset);
		sParaTemp.put("payment_type", payment_type);
		sParaTemp.put("notify_url", notify_url);
		sParaTemp.put("return_url", return_url);
		sParaTemp.put("seller_email", seller_email);
		sParaTemp.put("out_trade_no", out_trade_no);
		sParaTemp.put("subject", subject);
		sParaTemp.put("total_fee", total_fee);
		sParaTemp.put("body", body);
		sParaTemp.put("show_url", show_url);

		Map<String, String> result = new HashMap<String, String>();
		result.put("sign", getSign(sParaTemp));
		result.put("sign_type", AlipayConfig.sign_type);
		result.putAll(sParaTemp);

		// 建立请求
		String sHtmlText = AlipaySubmit.buildRequest(result, "get", "确认");
		try {
			this.getResponse().getWriter().println(sHtmlText);
			this.rechargesService.insertRecharges(getRecharges(out_trade_no,total_fee));
		} catch (IOException e) {
			loger.debug("支付宝失败信息请查看！");
			e.printStackTrace();
		}
		loger.debug("支付宝充值成功");

		return null;
	}
	
	private String getSign(final Map<String, String> map) {
		List<String> keys = new ArrayList<String>(map.keySet());
        Collections.sort(keys);//对参数排序，已确保拼接的签名顺序正确
        String prestr = "";
		boolean first = true;
		for (int i = 0; i < keys.size(); i++) {
			String key = (String) keys.get(i);
			String value = (String) map.get(key);
			if (value == null || value.trim().length() == 0) {
				continue;
			}
			if (first) {
				prestr = prestr + key + "=" + value;
				first = false;
			} else {
				prestr = prestr + "&" + key + "=" + value;
			}
		}
		return Md5Encrypt.md5(prestr+AlipayConfig.key);
	}

	private Recharges getRecharges(String tradeNo,String totalFee) {
		Recharges recharges = new Recharges();
		recharges.setId(getNewUUID());
		recharges.setUserId(getSessionUser().getUserId());
		recharges.setCreateTime(new Date());
		recharges.setUpdateTime(new Date());
		recharges.setStatus("正在充值....");
		recharges.setPayType("支付宝及时到账");
		recharges.setTradeNo(tradeNo);
		recharges.setTotalFee(totalFee);
		return recharges;
	}

	/**
	 * @return the totalFee
	 */
	public String getTotalFee() {
		return totalFee;
	}

	/**
	 * @param totalFee
	 *            the totalFee to set
	 */
	public void setTotalFee(String totalFee) {
		this.totalFee = totalFee;
	}

	public void setRechargesService(RechargesService rechargesService) {
		this.rechargesService = rechargesService;
	}
	

}